<?php

/*
 * DefinedFile 相关函数
 * @since 1.0 2014-9-2 by sutroon
 */

/**
 * 创建DefinedFile的表单UI代码
 * @param string $table
 * @since 1.0 2014-9-2 by sutroon
 */
function definedfile_to_formui_code($DATABASE_SET, $table, $fields = '') {
    $tab = "\t";
    $ln = PHP_EOL;
    $fields = str_replace(' ', '', $fields);
    $scripts = '';
    $hiddens = '';
    $enctype = '';
    $out = sotextareaencode('<div class="panel">{ln}{tab}<h3>编辑</h3>{ln}{tab}<form action="?s=Model/item_edit_save" method="post">{ln}{tab}<ul>'); // Head
    foreach ($DATABASE_SET as $row) {
        if ($row['TABLE_NAME'] == $table) {
            foreach ($row['TABLE_FIELDS'] as $row2) {
                if ($fields && !strpos(",$fields,", ',' . $row2['Field'] . ',')) {
                    continue;
                }
                $arrctrl = get_form_control_by_definedfile($row2);
                if (strlen($enctype) == 0 && strlen($arrctrl['enctype']) > 0) {
                    $enctype = $arrctrl['enctype'];
                }
                if ($arrctrl['scripts']) {
                    $scripts.=$arrctrl['scripts'];
                }
                $out.= $ln . $tab . $tab . '<li><label>' . $row2['AutoCoding']['Title'] . '：</label>' . $arrctrl['control'] . '</li>';
            }
        }
    }
    if ($scripts) {
        $scripts = $ln . '<script type="text/javascript">' . $ln . $scripts . '</script>';
    }
    if ($hiddens) {
        $hiddens = '{ln}{tab}' . $hiddens;
    }
    return $out . sotextareaencode('{ln}{tab}</ul>' . $hiddens . '{ln}{tab}</form>{ln}</div>' . $scripts);
}

/**
 * 创建DefinedFile的表格UI代码
 * @param string $table
 * @since 1.0 2014-9-2 by sutroon
 */
function definedfile_to_tableui_code($DATABASE_SET, $table, $fields = '') {
    $tab = "\t";
    $ln = PHP_EOL;
    $exSetting = array('fields' => '',);
    $fields = str_replace(' ', '', $fields);
    $out = sotextareaencode('<div class="table-panel">{ln}{tab}<div style="padding:5px;height:auto">{ln}{tab}{tab}<div style="margin-bottom:5px">{ln}{tab}{tab}{tab}<a href="?s=Model/item_edit.html" class="easyui-linkbutton lnk-add" iconCls="icon-add" plain="true">新增项目</a>{ln}{tab}{tab}{tab}<a href="?s=Model/item_edit/id/{key}.html" class="easyui-linkbutton lnk-edit" iconCls="icon-edit" plain="true">编辑项目</a>{ln}{tab}{tab}{tab}<a href="?s=Model/item_delete/id/{key}.html" class="easyui-linkbutton lnk-confirm" iconCls="icon-remove" plain="true">删除项目</a>{ln}{tab}{tab}{tab}<a href="#" class="easyui-linkbutton lnk-multiple" data-table=".table-list">批量操作</a>{ln}{tab}{tab}{tab}<a href="?s=Model/item_password_reset/id/{key}.html" class="easyui-linkbutton lnk-confirm" data-confirm="您确定要将密码重置为123456吗?">重置密码</a>{ln}{tab}{tab}</div>{ln}{tab}{tab}<div>{ln}{tab}{tab}{tab}<form method="post"><table><tr><td>名称: <input type="text" name="name" value="{$search.name}" /></td><td><a href="#" class="easyui-linkbutton btnSearch" iconCls="icon-search">搜索</a></td></tr></table></form>{ln}{tab}{tab}</div>{ln}{tab}</div>{ln}{tab}<table class="table-list" cellspacing="0" cellpadding="0" border="0" >{ln}');
    $str = '{ln}{tab}{tab}<tr>';
    foreach ($DATABASE_SET as $row) {
        if ($row['TABLE_NAME'] == $table) {
            $out.= $tab . $tab . '<tr>';
            foreach ($row['TABLE_FIELDS'] as $row2) {
                if ($fields && !strpos(",$fields,", ',' . $row2['Field'] . ',')) {
                    continue;
                }
                $out.= $ln . $tab . $tab . $tab . str_replace('{title}', $row2['AutoCoding']['Title'], '<th>{title}</th>');
                $str.='{ln}{tab}{tab}{tab}<td>{$vo.' . $row2['Field'] . ($row2['AutoCoding']['ListValueFunction'] ? '|' . $row2['AutoCoding']['ListValueFunction'] : '') . '}</td>';
            }
            $out.= $ln . $tab . $tab . '</tr>';
        }
    }
    $str.='{ln}{tab}{tab}</tr>';
    $out.= sotextareaencode('{ln}{tab}{tab}<foreach name="list" item="vo" >' . $str . '{ln}{tab}{tab}</foreach>');
    $out.= sotextareaencode('{ln}{tab}</table>{ln}{tab}{$page}{ln}</div>');
    return $out;
}

/**
 * 创建DefinedFile的MVC-Action代码
 * @param string $table
 * @since 1.0 2014-9-2 by sutroon
 */
function definedfile_to_mvccontrol_code($DATABASE_SET, $table, $fields = '', $view = 'setfile') {
    $tab = "\t";
    $ln = PHP_EOL.$tab;
    $fields = str_replace(' ', '', $fields);
    // delete
    if ($view == 'delete') {
        $out = '$id = I(\'id\');' . $ln;
        $out.='if (!$id) {' . $ln . $tab . '$this->result(false, \'参数无效!\');' . $ln . '}' . $ln;
        $out.='$M = M(\'' . $table . '\');' . $ln . '$result = $M->delete($id);' . $ln;
        $out.='if ($result === false) {' . $ln . $tab . '$this->result(false, \'删除%\');' . $ln . '} else {' . $ln . $tab . '$this->result(true, \'删除%\', \'?s=C/index.html\');' . $ln . '}' . $ln;
        return $out;
    }
    // list
    if ($view == 'list') {
        $out = '$params = create_params();' . $ln . '$params->addOptional(\'state\', \'number\', \'状态值无效!\');' . $ln . '$params->addOptional(\'name\');' . $ln . '$params->setExpression(\'name\', \'like\');' . $ln;
        $out.='$where = $params->getParams();' . $ln . '$show;' . $ln . '$list = get_paging_list(\'' . $table . '\', $where, $show,array(\'ORDERBY\'=>\'id desc\'));' . $ln;
        $out.='$this->assign(\'list\', $list);' . $ln . '$this->assign(\'page\', $show);' . $ln . '$this->assign(\'search\', format_exp_params($where));' . $ln . '$this->display();' . $ln;
        return $out;
    }
    // setfile
    if ($view == 'setfile') {
        $out = '$where[\'id\'] = I(\'id\');' . $ln . 'if (!$where[\'id\'])' . $ln . $tab . '$this->result(false, \'@参数有误!\');' . $ln . '$M = M(\'' . $table . '\');' . $ln . '$pwd = \'*\' . password(\'123456\');' . $ln . '$result = $M->where($where)->setField(\'password\', $pwd);' . $ln . '$this->result($result,\'@操作%!\');' . $ln;
        return $out;
    }
    // json-kv-list
    if ($view == 'json-kv-list') {
        $out = '$where[\'userType\']=\'ADMIN\';' . $ln . '$str = get_list_json(\'tuser_member\', $where, array(\'siteID\', \'concat(userName,"[",siteID,"]") as userName\'));' . $ln . '$this->ajaxReturn($str);' . $ln;
        return $out;
    }
    // json-list
    if ($view == 'json-list') {
        $out = '$where[\'userType\'] = \'ADMIN\';' . $ln . '$list = M(\'' . $table . '\')->where($where)->select();' . $ln . '$this->ajaxReturn($list);';
        return $out;
    }
    // json-item
    if ($view == 'json-item') {
        $out = '$id = I(\'id\');' . $ln . 'if (!$id) {' . $ln . $tab . 'die(\'\');' . $ln . '}' . $ln . '$data = M(\'' . $table . '\')->find($id);' . $ln . '$this->ajaxReturn($data);';
        return $out;
    }
    // json-delete
    if ($view == 'json-delete') {
        $out = '$id = I(\'id\');' . $ln . 'if (!$id) {' . $ln . $tab . '$this->ajaxReturn(array(\'success\' => false, \'message\' => \'参数有误!\'));' . $ln . $tab . 'return;' . $ln . '}';
        $out.='$result = M(\'tuser_member\')->delete($id);' . $ln . '$this->ajaxReturn($result ? array(\'success\' => true) : array(\'success\' => false, \'message\' => \'删除失败!\'));';
        return $out;
    }
    // edit
    $out = '$id=I(\'id\');' . $ln . '$params = create_params();' . $ln;
    $strP = '';
    $strO = '';
    $strD = '';
    $arrType = array('int' => 'number', 'flt' => 'double', 'str' => 'require', 'dat' => 'require');
    foreach ($DATABASE_SET as $row) {
        if ($row['TABLE_NAME'] == $table) {
            foreach ($row['TABLE_FIELDS'] as $row2) {
                if ($fields && !strpos(",$fields,", ',' . $row2['Field'] . ',')) {
                    continue;
                }
                if ($row2['Field'] == 'id') {
                    continue;
                }
                $type = get_field_alias_type($row2['Type']);
                if ($row2['AutoCoding']['ParamAddParam']) {
                    $strP.='$params->addParam(\'' . $row2['Field'] . '\', \'' . $arrType[$type] . '\', \'' . $row2['AutoCoding']['Title'] . '必需填写!\');' . $ln;
                } else if ($row2['AutoCoding']['ParamAddOptional']) {
                    $strO.='$params->addOptional(\'' . $row2['Field'] . '\', \'' . $arrType[$type] . '\', \'' . $row2['AutoCoding']['Title'] . '无效!\');' . $ln;
                } else if ($row2['AutoCoding']['ParamAddData']) {
                    $strD.='$params->addData(\'' . $row2['Field'] . '\');' . $ln;
                } else if ($row2['AutoCoding']['ParamConfirm']) {
                    $strP.='$params->confirm_param(I(\'' . $row2['Field'] . '\'), I(\'re' . $row2['Field'] . '\'), \'两次' . $row2['AutoCoding']['Title'] . '输入不一致!\');';
                }
            }
        }
    }
    $out.=$strP . $strO . $ln . '// 校验表单参数' . $ln . 'if ($params->hasError()) {' . $ln . $tab . '$this->error($params->getError());' . $ln . '}' . $strD . $ln;
    $out.='if ($id) {' . $ln . $tab . '// 编辑项目' . $ln . $tab . '$params->addData(\'id\', $id);' . $ln . $tab . '$result = $M->save($params->getParams());' . $ln . '} else {' . $ln . $tab . '// 创建项目' . $ln . $tab . '$result = $M->add($params->getParams());' . $ln . '}' . $ln;
    $out.='$this->result($result, \'保存%!\', array(\'\', \'?s=C/index.html\'));';
    return $out;
}

/**
 * 获取DefinedFile的表单域控件
 * @param array $row
 * @return array
 * @since 1.0 2014-9-1 by sutroon
 */
function get_form_control_by_definedfile($row) {
    $ctrl = '';
    $hidinputs = '';
    $scripts = '';
    $formtype = '';
    $rowAutoCoding = $row['AutoCoding'];
    $require = $rowAutoCoding['FormRequire'] ? ' required' : '';
    $value = '{' . $rowAutoCoding['FormValueVar'] . '.' . $row['Field'] . '}';
    switch ($rowAutoCoding['FormInputType']) {
        case 'text':
            $ctrl = '<input type="text" name="' . $row['Field'] . '" placeholder="请输入' . $rowAutoCoding['Title'] . '" value="' . $value . '" title="请输入' . $rowAutoCoding['Title'] . '"' . $require . ' />';
            break;
        case 'hidden':
            $hidinputs .= '\n<input type="hidden" name="' + $row['Field'] + '" value="' + $value + '" />';
            break;
        case 'password':
            $ctrl = '<input type="text" name="' . $row['Field'] . '" placeholder="请输入' . $rowAutoCoding['Title'] . '" value="' . $value . '" title="请输入' . $rowAutoCoding['Title'] . '"' . $require . ' />';
            if ($rowAutoCoding['FormValueVar']) {
                $scripts .= "$('input[name=\"" . $row['Field'] . "\"]').val('" . $value . "');";
            }
            break;
        case 'file':
            $formtype = ' enctype="multipart/form-data" ';
            $ctrl = '<input type="file" name="' . $row['Field'] . '" data-value="' . $value . '" />';
            break;
        case 'textarea':
            $ctrl = '<textarea name="' . $row['Field'] . '" placeholder="请输入' . $rowAutoCoding['Title'] . '" title="请输入' . $rowAutoCoding['Title'] . '"' . $require . '>' . $value . '</textarea>';
            break;
        case 'editor':
            $ctrl = '<textarea name="' . $row['Field'] . '" placeholder="请输入' . $rowAutoCoding['Title'] . '" title="请输入' . $rowAutoCoding['Title'] . '"' . $require . ' class="editor">' . $value . '</textarea>';
            break;
        case 'select':
            $ctrl = '<select name="' . $row['Field'] . '" title="请选择' . $rowAutoCoding['Title'] . '"' . $require . '>' . generate_group_option_by_definedfile($rowAutoCoding['FormValueRange']) . '</select>';
            if ($rowAutoCoding['FormJSONSource']) {
                $scripts .= "JQUIHelper.load_options('select[name=\"" . $row['Field'] . "\"]', '" . $rowAutoCoding['FormJSONSource'] . "', '请选择" . $rowAutoCoding['Title'] . "','" . $value . "');" . PHP_EOL;
            } else {
                if ($rowAutoCoding['FormValueVar']) {
                    $scripts .= "$('select[name=\"" . $row['Field'] . "\"]').find('option[value=\"" . $value . "\"]').prop('selected',true);" . PHP_EOL;
                }
            }
            break;
        case 'radio':
        case 'checkbox':
            $ctrl = generate_group_input_by_definedfile($rowAutoCoding['FormInputType'], $rowAutoCoding['FormValueRange'], $row['Field'], $rowAutoCoding['Title'], $require);
            if ($rowAutoCoding['FormValueVar']) {
                $scripts .= "$('input[name=\"" . $row['Field'] . "\"][value=\"" . $value . "\"]').prop('checked',true);" . PHP_EOL;
            }
            break;
        case 'timepicker':
            $ctrl = '<input type="text" name="' . $row['Field'] . '" class="timepicker" value="' . $value . '" title="请选择' . $rowAutoCoding['Title'] . '"' . $require . ' />';
            break;
        case 'datepicker':
            $ctrl = '<input type="text" name="' . $row['Field'] . '" class="datepicker" value="' . $value . '" title="请选择' . $rowAutoCoding['Title'] . '"' . $require . ' />';
            break;
    }
    return array('control' => $ctrl, 'enctype' => $formtype, 'scripts' => $scripts, 'hiddens' => $hidinputs);
}

/**
 * 生成DefinedFile的option控件
 * @param {string} data 数据源,如:1=启动&2=暂停&!0=停止, 值前面加符号[!]表示选中
 * @returns {String}
 * @since 1.0 2014-7-21 by sutroon
 */
function generate_group_option_by_definedfile($data) {
    if (!$data) {
        return '';
    }
    $arr = explode('&', $data);
    $item = '';
    $str = '';
    $checked = '';
    for ($i = 0; $i < count($arr); $i++) {
        $item = explode('=', $arr[$i]);
        $checked = ($item[0][0] == '!') ? ' selected="selected"' : '';
        $item[0] = $item[0] . substr(1);
        $str .= '<option value="' + $item[0] + '"' + $checked + '>' + $item[1] + '</option>';
    }
    return $str;
}

/**
 * 生成DefinedFile的radio或checkbox控件
 * @param {string} type 控件类型,如:radio,checkbox
 * @param {string} data 数据源,如:1=启动&2=暂停&!0=停止, 值前面加符号[!]表示选中
 * @param {string} field 表单域名称,即字段名称,如: name
 * @param {string} label 表单域描述,如: 名称
 * @param {string} required 是否必填项目, 如: required
 * @returns {string}
 * @since 1.0 2014-7-21 by sutroon
 */
function generate_group_input_by_definedfile($type, $data, $field, $label, $required) {
    if (!$data) {
        return '';
    }
    $arr = explode(strpos('&', $data) ? '&' : ',', $data);
    $item = '';
    $str = '';
    $checked = '';
    for ($i = 0; $i < count($arr); $i++) {
        $item = explode('=', $arr[$i]);
        if ($item[0][0] == '!') {
            $checked = ' checked="checked"';
            $item[0] = substr($item[0], 1);
        } else {
            $checked = '';
        }
        $str += '<input type="' + $type + '" name="' + $field + '" value="' + $item[0] + '" title="请选择' + $label + '"' + $checked + $required + ' />' + $item[1] + PHP_EOL;
    }
    return $str;
}
